package com.tianzj.boot.mvc.controller.base;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.tianzj.boot.annotation.Log;
import com.tianzj.boot.mvc.entity.system.SysMenu;
import com.tianzj.boot.mvc.entity.system.SysUser;
import com.tianzj.boot.mvc.service.system.SysMenuService;
import com.tianzj.boot.util.ExceptionMsg;
import com.tianzj.boot.util.tree.Tree;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class LoginController {

	@Autowired
	private SysMenuService sysMenuService;
	
	//登录页
	@RequestMapping("/")
	public ModelAndView index(){
		return new ModelAndView("login");
	}
	
	//登录方法
	@RequestMapping("/login")
	@Log(value="登录方法")
	public ModelAndView login(SysUser user,Model model){
	   UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            SysUser sysUser=(SysUser) subject.getPrincipal();
            Session session = SecurityUtils.getSubject().getSession();
            session.setAttribute("sessionUser",sysUser);
            //重定向到showIndex
           return new ModelAndView("redirect:/showIndex");
        }catch (AuthenticationException e){
        	log.info("认证失败");
        	model.addAttribute("errormsg",ExceptionMsg.LoginNameOrPassWordError.getMsg());
        }catch (Exception e){
        	log.info("登陆失败====》"+user.getUserName());
        	model.addAttribute("errormsg",ExceptionMsg.LoginNameOrPassWordError.getMsg());
        }
        //去掉session
        SecurityUtils.getSubject().logout();
		return new ModelAndView("redirect:/");
	}
	//登录方法
	@RequestMapping("/showIndex")
	public ModelAndView showIndex(SysUser user,Model model){
		SysUser sysUser =(SysUser) SecurityUtils.getSubject().getSession().getAttribute("sessionUser");
		List<Tree<SysMenu>> menus = sysMenuService.listMenuTree(sysUser.getId());
		model.addAttribute("menus", menus);
		return new ModelAndView("index");
	}
	

    @GetMapping("/logOut")
    public ModelAndView logOut() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new ModelAndView("redirect:/");
    }
	
	//首页
	@RequestMapping("/main")
	public ModelAndView main(){
		return new ModelAndView("main");
	}
}
